<template>
  <div class="app-container">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="待传输" name="first">
        <!--顶部搜索-->
        <div class="search-container">
          <div class="btn-container">
            <el-row :gutter="10">
              <el-col :span="1.5">
                <el-button
                  type="primary"
                  @click="uploadInner"
                  v-hasPermi="['system:application:add']"
                >摆渡到内网
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  @click="batchDel"
                  v-hasPermi="['system:application:type']"
                >批量删除
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  @click="selectFile"
                  v-hasPermi="['system:application:type']"
                >文件选择
                </el-button>
              </el-col>
            </el-row>
          </div>
        </div>
<!--
        <div v-for="(item, i) in tempList" :key="i">
          <div>{{item.speed}}</div>
        </div>-->

        <!--列表-->
        <el-table v-loading="loading" :data="tempList" @selection-change="handleSelectionChange" :key="tempKey">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="文件名" align="center" prop="fileName" width="320" :show-overflow-tooltip="true"/>
          <el-table-column label="进度" align="center" width="320" prop="speed">
            <template slot-scope="scope">
<!--              <div>{{scope.row.speed}}</div>-->
              <el-progress :percentage="scope.row.speed"></el-progress>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.startTime) }}</span>
            </template>
          </el-table-column>
        </el-table>

        <el-dialog
          title="导入"
          :visible.sync="open"
          :close-on-click-modal="false"
          close-on-press-escape
          destroy-on-close
          width="550px"
        >
          <el-upload
            class="upload-demo"
            drag
            :action="uploadUrl"
            :headers="headers"
            :on-preview="handlePreview"
            :before-upload="beforeUpload"
            :on-success="handleSuccess"
            :file-list="fileList"
            :show-file-list="true"
            accept=".png, .jpg, .jpeg, .mp3, .mp4, .avi, .txt, .doc, .docx, .pdf, .xls, .xlsx"
            multiple>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">仅允许导入PNG、JPG、JPEG、MP3、WAV、MP4、AVI、TXT、DOC、DOCX、pdf、xls、xlsx格式文件。</div>
          </el-upload>
        </el-dialog>

      </el-tab-pane>
      <el-tab-pane label="历史记录" name="second">

        <!--顶部搜索-->
        <div class="search-container">
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
            <el-form-item prop="fileName">
              <el-input
                v-model="queryParams.fileName"
                placeholder="请输入文件名"
                clearable
                style="width: 240px"
                @keyup.enter.native="handleQuery"
              />
              <el-input
                v-model="queryParams.fileName"
                placeholder="请输入文件名"
                clearable
                style="width: 240px; display: none"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-form>
          <!--<div class="btn-container">
            <el-row :gutter="10">
              <el-col :span="1.5">
                <el-button
                  type="primary"
                  icon="el-icon-plus"
                  size="mini"
                  @click="handleQuery"
                  v-hasPermi="['system:application:add']"
                >搜索
                </el-button>
              </el-col>

            </el-row>
          </div>-->
        </div>


        <el-table v-loading="loading" :data="hisList">
          <el-table-column label="文件名" align="center" prop="fileName" width="320" :show-overflow-tooltip="true"/>
          <el-table-column label="状态" align="center" width="320" prop="uploadStatus">
            <template slot-scope="scope">
              <!--<div class="percent-container">
                <div class="upload-percent">
                  &lt;!&ndash;                  <div class="percent-text">0%</div>&ndash;&gt;
                </div>
                <div class="percent-text-out">0%</div>
              </div>-->
              <span style="color: #67c23a">上传成功</span>
            </template>
          </el-table-column>
          <el-table-column label="开始时间" align="center" prop="createTime">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.startTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="结束时间" align="center" prop="createTime">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.endTime) }}</span>
            </template>
          </el-table-column>
        </el-table>
        <!--分页-->
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
  import {getTempList, delFile, getHistoryList, moveFiles} from "@/api/system/upload"
  import {getToken} from "@/utils/auth";
  import {deepClone} from "../../../utils";

  export default {
    name: "index",
    data() {
      return {
        activeName: 'first',
        tempList: [],
        tempKey: null,
        open: false,
        title: '导入',
        uploadUrl: process.env.VUE_APP_BASE_API + "/file-history/add", // 上传的图片服务器地址
        headers: {
          Authorization: "Bearer " + getToken()
        },
        fileList: [],
        loading: false,
        delList: [],
        //查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
        },
        hisList: [],
        total: 0,
        maxSize: 100,
        isSuccess: false,
        timer: null,
      }
    },
    created() {
      this.getList()
    },
    methods: {
      handleClick(tab, event) {
        if (tab.name === 'second') {
          this.handleQuery()
        } else {
          this.getList()
        }
      },
      setProgress() {
        this.timer = setInterval(() => {
          this.getDataChange()
        }, 1)
      },

      getDataChange() {
        this.$nextTick(() => {
          let temp = this.tempList.map(e => {
            if(e.speed <= 98) {
              setTimeout(() => {
                e.speed += 1;
              }, 0)
            }else {
              clearInterval(this.timer)
            }
            return e
          })
          this.tempList = []
          this.tempKey = Math.random()
          this.tempList = temp
        })
      },
      //上传到内网
      uploadInner() {
        this.setProgress()
        moveFiles().then(res => {
          if(res.code === 200 && res.data) {
            this.isSuccess = true
            this.$message.success('上传成功')
            this.getList()
            clearInterval(this.timer)
          }else {
            clearInterval(this.timer)
            this.$message.error(res.msg)
          }
        }).catch(err => {
          this.$message.error(err)
          clearInterval(this.timer)
        })
       /*if(this.delList.length > 0) {


       }else {
         this.$message.success('请选择需要摆渡的文件')
       }*/
      },

      //获取传送进度
/*      getUploadSpeed(speed) {
        let progs = speed ? speed : 0
        setTimeout(() => {
          progs += 1
        }, 10)
        return progs;
      },*/
      //批量删除
      batchDel() {
        if(this.delList.length > 0) {
          this.$confirm('此操作将永久删除该文件, 是否继续？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            delFile(this.delList).then(res => {
              if (res.code === 200 && res.data) {
                this.$message.success('删除成功')
                this.getList()
              } else {
                this.$message.error(res.msg)
              }
            }).catch(err => {
              this.$message.error(err)
            })
          }).catch(() => {});
        } else {
          this.$message.warning('请选择要删除的文件')
        }
      },
      //选择文件
      selectFile() {
        this.open = true
      },

      //获取列表
      getList() {
        getTempList().then(res => {
          if (res.code === 200) {
            this.tempList = res.data
            this.tempList.forEach(e => {
              e.speed = 0
            })
          } else {
            this.$message.error(res.msg)
          }
        }).catch(err => {
          this.$message.error(err)
        })
      },

      handleSelectionChange(e) {
        this.delList = e.map(item => {
          return item.fileTempId
        })
        console.log(this.delList)
      },

      //上传文件
      handlePreview(file) {

      },

      //开始上传
      beforeUpload(file) {
        if (file.size / 1024 / 1024 > this.maxSize) {
          this.$message.error({
            message: `上传文件大小不能超过${this.maxSize}M!`,
          });
          return false;
        }
      },
      //上传文件成功
      handleSuccess(response, file, fileList) {
        if(response.code === 200 && response.data) {
          this.$message.success("上传成功")
          this.getList()
        }else {
          console.log(response, file, fileList)
          let index = fileList.indexOf(file)
          console.log(index)
          fileList.splice(index, 1)
          this.$message.error(response.msg)
        }

      },

      handleQuery() {
        this.queryParams.pageNum = 1
        this.getHisList()
      },

      getHisList() {
        getHistoryList(this.queryParams).then(res => {
          if (res.code === 200) {
            this.hisList = res.rows
          } else {
            this.$message.error(res.msg)
          }
        }).catch(err => {
          this.$message.error(err)
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .search-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 21px;

    ::v-deep .el-form-item {
      margin-bottom: 0 !important;
    }

    .btn-container {
      display: flex;
      align-items: center;
    }
  }

  .upload-demo {
    display: flex;
    align-items: center;
    flex-direction: column;
  }

  .percent-container {
    width: 300px;
    height: 30px;
    border-radius: 15px;
    background: #ebeef5;
    display: flex;
    align-items: center;

    .upload-percent {
      height: 30px;
      border-radius: 15px;
      background: #409eff;
      display: flex;
      align-items: center;
      justify-content: flex-end;

      .percent-text {
        font-size: 12px;
        color: #FFFFFF;
      }
    }

    .percent-text-out {
      font-size: 12px;
      color: #FFFFFF;
      margin-left: 16px;
    }

  }

  ::v-deep .el-dialog__body {
    display: flex;
    align-items: center;
    justify-content: center;
  }
</style>
